IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[udf_GetKiHieuNhapXuat]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[udf_GetKiHieuNhapXuat]
GO
CREATE FUNCTION [udf_GetKiHieuNhapXuat](
@Loai_nhap_xuat int
)
RETURNS varchar(8)
AS
BEGIN
	DECLARE @Return varchar(8)
	DECLARE @Sum int
	SELECT @Sum = COUNT(ID) FROM PhieuNhapXuat WHERE DAY(Ngay_cap_nhat_cuoi) = DAY(GETDATE()) AND Loai_nhap_xuat = @Loai_nhap_xuat 
	
	IF @Sum < 10
	BEGIN
		SET @Return = '000' + CONVERT(varchar(8),@Sum)
	END

	ELSE IF @Sum < 100
	BEGIN
		SET @Return = '00' + CONVERT(varchar( 8), @Sum)
	END
	ELSE IF @Sum < 1000
	BEGIN
		SET @Return = '0' + CONVERT(varchar(8), @Sum)
	END

RETURN @Return
END